import paramiko
import openpyxl

def read_devices_from_excel(filename):
    wb = openpyxl.load_workbook(filename)
    ws = wb.active
    devices = []
    for row in ws.iter_rows(min_row=2, values_only=True):
        ip, username, password, command = row[:4]
        if ip and username and password and command:
            devices.append({
                "ip": ip,
                "username": username,
                "password": password,
                "command": command
            })
    return devices

def ssh_and_run_linux(dev):
    ip = dev["ip"]
    username = dev["username"]
    password = dev["password"]
    command = dev["command"]
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(ip, username=username, password=password, timeout=10)
        print(f"[{ip}] 执行命令: {command}")
        stdin, stdout, stderr = ssh.exec_command(command)
        output = stdout.read().decode(errors="ignore")
        error = stderr.read().decode(errors="ignore")
        print(f"[{ip}] 输出:\n{output}")
        if error:
            print(f"[{ip}] 错误:\n{error}")
        ssh.close()
    except Exception as e:
        print(f"[{ip}] 连接失败: {e}")

if __name__ == "__main__":
    devices = read_devices_from_excel("devices.xlsx")
    for dev in devices:
        ssh_and_run_linux(dev)